package com.foreveross.crawl.adapter.sub.impl20140402.v3;

import java.net.URI;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;

import com.foreveross.crawl.adapter.AbstractAdapter;
import com.foreveross.crawl.adapter.sub.impl20140402.v3.airfrance.AirfranceRoundV3;
import com.foreveross.crawl.domain.airfreight.doub.DoublePlaneInfoEntity;
import com.foreveross.crawl.exception.NoTicketException;
import com.foreveross.taskservice.common.bean.TaskModel;
@SuppressWarnings("deprecation")
public class AirfranceAdapterV3 extends AbstractAdapter{
	private static final String peopleNum = "1";//乘坐人数
	private static final String CHAR_SET = "UTF-8";
	private static final String REQUEST_HOST = "www.airfrance.com.cn";
	private static final String REQUEST_PATH = "/cgi-bin/AF/CN/zh/local/process/standardbooking/ValidateSearchAction.do";
	private static final String REQUEST_PATH_2 = "/cgi-bin/AF/CN/zh/local/process/standardbooking/DisplayFlightPageAction.do";
	private List<DoublePlaneInfoEntity> planeInfos = new ArrayList<DoublePlaneInfoEntity>();
	private Long sleepTime = 5000L;
	public static enum CabinType {
//		Y_MCHER("经济舱（最低票价） Economy"), F_MCHER("头等舱 La Premiere"), C_MCHER("商务舱 Business"), W_MCHER("尊尚经济舱 Premium Economy"), Y_FLEX("经济舱 (可免费更改) Economy");
		Y_MCHER("经济舱（最低票价） Economy");
//		Y_FLEX("经济舱 (可免费更改) Economy"),
//		C_MCHER("商务舱 Business");	
		private String lable;
		
		CabinType(String lable) {
			this.lable = lable;
		}
		
		public String getLable() {
			return this.lable;
		}
	}
	
	public AirfranceAdapterV3(TaskModel taskQueue) {
		super(taskQueue);
	}
	
	public static void main(String[] args) throws Exception {
		TaskModel tm = new TaskModel();
		tm.setFromCity("PEK");
		tm.setFromCityName("北京");
		tm.setToCity("CDG");
		tm.setToCityName("巴黎");
		tm.setFlightDate("2015-02-14");
		tm.setReturnGrabDate("2015-03-01");
		tm.setIsInternational(1);
		tm.setIsReturn(1);
		Object content = null;
		AirfranceAdapterV3 afa = new AirfranceAdapterV3(tm);
		content = afa.fetch();
		afa.printJson((List<?>) content, "d:/aa3.txt");
	}

	private URI produceUri(CabinType cabin ,String url) throws Exception {
		Calendar cal  = Calendar.getInstance();
		Date gradDate  = DateUtils.parseDate(taskQueue.getFlightDate(), "yyyy-MM-dd");
		cal.setTime(gradDate);
		List<NameValuePair> qparams = new ArrayList<NameValuePair>();
		qparams.add(new BasicNameValuePair("arrival", taskQueue.getToCity()));
		qparams.add(new BasicNameValuePair("arrival", taskQueue.getFromCity()));
		qparams.add(new BasicNameValuePair("cabin", cabin.toString().substring(0,1)));
		qparams.add(new BasicNameValuePair("dayDate", taskQueue.getFlightDate().split("-")[2]));//19
		qparams.add(new BasicNameValuePair("dayDate", taskQueue.getReturnGrabDate().split("-")[2]));//25
		qparams.add(new BasicNameValuePair("departure", taskQueue.getFromCity()));//pvg
		qparams.add(new BasicNameValuePair("departure", taskQueue.getToCity()));//cdg
		qparams.add(new BasicNameValuePair("familyTrip", "NON"));
		qparams.add(new BasicNameValuePair("haul", "LH"));
		
		qparams.add(new BasicNameValuePair("idArrivalTrip1Lib",taskQueue.getToCityName()+" ("+taskQueue.getToCity()+") "));
		qparams.add(new BasicNameValuePair("idArrivalTrip1LibContainer",taskQueue.getToCity()));
		qparams.add(new BasicNameValuePair("idDepartureTrip1Lib",taskQueue.getFromCityName()+" ("+taskQueue.getFromCity()+") "));
		qparams.add(new BasicNameValuePair("idDepartureTrip1LibContainer",taskQueue.getFromCity()));	
		
		qparams.add(new BasicNameValuePair("isUM", ""));
		
		qparams.add(new BasicNameValuePair("jourAllerFin", "20"));
		qparams.add(new BasicNameValuePair("jourAllerOrigine", "25"));
		qparams.add(new BasicNameValuePair("moisAllerFin", taskQueue.getFlightDate().split("-")[0]+taskQueue.getFlightDate().split("-")[1]));
		qparams.add(new BasicNameValuePair("moisAllerOrigine", taskQueue.getReturnGrabDate().split("-")[0]+taskQueue.getFlightDate().split("-")[1]));
		qparams.add(new BasicNameValuePair("nbEnfants", ""));
		
		qparams.add(new BasicNameValuePair("nbPassenger", peopleNum));//1
		qparams.add(new BasicNameValuePair("paxTypoList", "ADT"));
		qparams.add(new BasicNameValuePair("paxTypoList", "ADT"));
		
		qparams.add(new BasicNameValuePair("paxTypoList", "ADT"));
		qparams.add(new BasicNameValuePair("paxTypoList", "ADT"));
		qparams.add(new BasicNameValuePair("plusOptions", ""));
		qparams.add(new BasicNameValuePair("selectCabin", cabin.toString()));
		qparams.add(new BasicNameValuePair("selectCabin", cabin.toString()));
		
		qparams.add(new BasicNameValuePair("selectCabin", cabin.toString()));
		qparams.add(new BasicNameValuePair("selectCabin", cabin.toString()));//"Y_MCHER"
		qparams.add(new BasicNameValuePair("subCabin", cabin.toString().split("_")[1]));
		
//		qparams.add(new BasicNameValuePair("selectPreviousSearch", taskQueue.getFromCity()+"-"+taskQueue.getToCity()
//				+"_"+taskQueue.getFlightDate().split("-")[0]+String.valueOf((Integer.parseInt(taskQueue.getFlightDate().split("-")[1])-1))+taskQueue.getFlightDate().split("-")[2]));//"PVG-CDG_20141119"
		
		qparams.add(new BasicNameValuePair("typeTrip", "2"));
		qparams.add(new BasicNameValuePair("yearMonthDate", taskQueue.getFlightDate().split("-")[0]+taskQueue.getFlightDate().split("-")[1]));//201412
		qparams.add(new BasicNameValuePair("yearMonthDate", taskQueue.getReturnGrabDate().split("-")[0]+taskQueue.getReturnGrabDate().split("-")[1]));
		return URIUtils.createURI("http", REQUEST_HOST, -1, url, URLEncodedUtils.format(qparams, CHAR_SET), null);
	}
	
	@Override
	public Object fetch(String arg0) throws Exception {
		switch (super.getRouteType()) {
		case INTERNATIONAL_ROUND:
			return fetch();
		}
		return null;
	}
	/**
	 * 抓取数据
	 * @return
	 * @throws Exception
	 */
	public Object fetch() throws Exception {
		HttpPost request = null;
		Object html = "";
		Map<CabinType ,String >resulMap=new HashMap<CabinType, String>();
		for(CabinType cabin : CabinType.values()) {
			List<DoublePlaneInfoEntity> planeInfo = new ArrayList<DoublePlaneInfoEntity>();
			request=new HttpPost(produceUri(cabin,REQUEST_PATH));
			setPostHeadInfo(request, "http://www.airfrance.com.cn/CN/zh/common/home/home/HomePageAction.do");
			html=this.excuteRequest(request);
			super.appendPageContents(html.toString());
			super.setLenghtCount( html.toString().length());
			if(validateFetch(html)){ // 验证
				Thread.sleep(sleepTime);
				request =new HttpPost(produceUri(cabin,REQUEST_PATH_2));
				setPostHeadInfo(request, "http://www.airfrance.com.cn/cgi-bin/AF/CN/zh/local/process/standardbooking/ValidateSearchAction.do");
				html = this.excuteRequest(request);// 获取页面
				super.appendPageContents(html.toString());
				super.setLenghtCount(html.toString().length());
				validateFetch(html); // 验证
				logger.info("抓取完成!");
				resulMap.put(cabin, html.toString());
				AirfranceRoundV3 afr3 = new AirfranceRoundV3();
				planeInfo = afr3.flightInfoAssembly(html.toString(),cabin,taskQueue);
				if(planeInfo.size()>0){
					planeInfos.addAll(planeInfo);
				}
			}
		}
		if(planeInfos.size()>0)return planeInfos;
		else return null;
	}
	
	
	
	
	@Override
	public String getUrl() throws Exception {		
		StringBuffer url = new StringBuffer("http://www.airfrance.com.cn/cgi-bin/AF/CN/zh/local/process/standardbooking/DisplayFlightPageAction.do?arrival=CDG&arrival=PVG&cabin=Y&cabinCIO=Y&cabinLH=Y&cabinMH=Y&cabinSH=Y&countries=&dayDate=19&dayDate=25&departure=PVG&departure=CDG&haul=LH&idArrivalTrip1Lib=%E5%B7%B4%E9%BB%8E%2C%20Charles%20de%20Gaulle%20(CDG)%20-%20%E6%B3%95%E5%9B%BD&idDepartureTrip1Lib=%E4%B8%8A%E6%B5%B7%2C%20%E6%B5%A6%E4%B8%9C%E6%9C%BA%E5%9C%BA%20(PVG)%20-%20%E4%B8%AD%E5%9B%BD&isUM=&jourAllerFin=11&jourAllerOrigine=16&method=getNewCalendarFlightData&moisAllerFin=201512&moisAllerOrigine=201412&nbEnfants=&nbPassenger=1&paxTypoList=ADT&paxTypoList=ADT&paxTypoList=ADT&paxTypoList=ADT&paxTypoList=ADT&paxTypoList=ADT&paxTypoList=ADT&paxTypoList=ADT&paxTypoList=ADT&selectPreviousSearch=&subCabin=MCHER&typeTrip=2&yearMonthDate=201412&yearMonthDate=201412");
		return url.toString();
	}

	/**
	 * 设置请求头信息
	 * 
	 * @param post
	 */
	private void setPostHeadInfo(HttpPost httpPost,String postUrl) {
		httpPost.setHeader("Host", "www.airfrance.com.cn");
		httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; rv:31.0) Gecko/20100101 Firefox/34.0");
		httpPost.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		httpPost.setHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
		httpPost.setHeader("Referer",postUrl);
	}
	
	@Override
	public List<Object> paraseToVo(Object obj) throws Exception {
		switch (super.getRouteType()) {
		case INTERNATIONAL_ROUND:
			return (List<Object>) obj;
//			return new AirfranceRoundV3().flightInfoAssembly((Map<CabinType, String>) obj, taskQueue);//国际往返
		}
		return null;
	}

	@Override
	public boolean validateFetch(Object arg0) throws Exception {
		if(arg0.toString() == null) {
			throw new Exception("数据抓取为空");
		}else if(arg0.toString().contains("选择的日期没有航班")){
			throw new NoTicketException("该日期没有航班");
		}
		return true;
	}

	
}
